<template>
  <div class="product-list-container agri-page-container">
    <div class="page-header agri-page-header">
      <div class="page-title agri-page-title">
        <el-icon><ShoppingBag /></el-icon>
        <span>农产品市场</span>
      </div>
      <div class="page-actions agri-page-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索产品名称或类型"
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card agri-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="产品类型">
          <el-select v-model="filterForm.productType" placeholder="全部类型" clearable>
            <el-option label="粮食" value="粮食" />
            <el-option label="蔬菜" value="蔬菜" />
            <el-option label="水果" value="水果" />
            <el-option label="肉类" value="肉类" />
            <el-option label="禽蛋" value="禽蛋" />
            <el-option label="水产" value="水产" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-select v-model="filterForm.priceRange" placeholder="全部价格" clearable>
            <el-option label="0-10元" value="0-10" />
            <el-option label="10-30元" value="10-30" />
            <el-option label="30-50元" value="30-50" />
            <el-option label="50元以上" value="50+" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-select v-model="filterForm.sort" placeholder="默认排序">
            <el-option label="价格从低到高" value="priceAsc" />
            <el-option label="价格从高到低" value="priceDesc" />
            <el-option label="销量从高到低" value="salesDesc" />
            <el-option label="最新上架" value="timeDesc" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilter">
            <el-icon><Filter /></el-icon> 筛选
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 产品列表 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="filteredProducts.length === 0" class="empty-data">
      <el-empty description="未找到符合条件的产品" />
    </div>
    
    <div v-else class="product-grid">
      <el-row :gutter="20">
        <el-col v-for="product in displayedProducts" :key="product.id" 
                :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-card class="product-card agri-card" shadow="hover" @click="viewProductDetail(product)">
            <div class="product-image-container">
              <img 
                :src="formatImageUrl(product.image)" 
                class="product-image" 
                alt="产品图片" 
              />
            </div>
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
             
              <div class="product-price">¥{{ product.price }}<span class="product-unit">/ {{ product.unit }}</span></div>
              <div class="product-stock">库存: <span :class="{'stock-highlight': product.stock > 0, 'stock-out': !product.stock || product.stock <= 0}">{{ product.stock || 0 }}</span> {{ product.unit }}</div>
              <div class="product-farmer">
                <div class="farmer-avatar">
                  <el-avatar :size="24" :src="product.farmerAvatar">
                    {{ product.farmerName ? product.farmerName.substring(0, 1) : 'F' }}
                  </el-avatar>
                </div>
                <span class="farmer-name">{{ product.farmerName }}</span>
              </div>
              <div class="product-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click.stop="createOrder(product)"
                  :disabled="!product.stock || product.stock <= 0"
                >
                  {{ product.stock && product.stock > 0 ? '立即购买' : '已售罄' }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="filteredProducts.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 产品详情对话框 -->
    <el-dialog
      v-model="productDetailVisible"
      title="产品详情"
      width="60%"
      destroy-on-close
    >
      <div class="product-detail">
        <div class="product-detail-image">
          <el-image :src="formatImageUrl(currentProduct.image)" fit="contain">
            <template #error>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
                <span>暂无图片</span>
              </div>
            </template>
          </el-image>
        </div>
        
        <div class="product-detail-content">
          <el-descriptions title="产品详情" :column="2" border>
            <el-descriptions-item label="产品名称">{{ currentProduct.name }}</el-descriptions-item>
            <el-descriptions-item label="产品价格">¥{{ currentProduct.price }} / {{ currentProduct.unit }}</el-descriptions-item>
            <el-descriptions-item label="库存数量">{{ currentProduct.stock }} {{ currentProduct.unit }}</el-descriptions-item>
            <el-descriptions-item label="销售数量">{{ currentProduct.salesCount || 0 }} {{ currentProduct.unit }}</el-descriptions-item>
            
            <!-- 根据产品来源显示不同的信息 -->
            <template v-if="currentProduct.sellerType === 'seller'">
              <!-- 卖家产品(肥料)特有信息 -->
              <el-descriptions-item label="产品产地">{{ currentProduct.origin || '未知' }}</el-descriptions-item>
              <el-descriptions-item label="生产日期">{{ currentProduct.productionDate || '未知' }}</el-descriptions-item>
              <el-descriptions-item label="保质期">{{ currentProduct.shelfLife ? `${currentProduct.shelfLife}天` : '未知' }}</el-descriptions-item>
            </template>
            
            <template v-else>
              <!-- 农户产品特有信息 -->
              <el-descriptions-item label="种植方式">{{ currentProduct.plantingMethod || '常规种植' }}</el-descriptions-item>
              <el-descriptions-item label="收获时间">{{ currentProduct.harvestDate || '当季新鲜' }}</el-descriptions-item>
              <el-descriptions-item label="新鲜程度">{{ currentProduct.freshnessDays ? `保鲜${currentProduct.freshnessDays}天` : '新鲜采摘' }}</el-descriptions-item>
            </template>
            
            <el-descriptions-item label="产品描述" :span="2">{{ currentProduct.description || '暂无描述' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>

    <!-- 创建订单对话框 -->
    <el-dialog
      v-model="orderDialogVisible"
      title="创建订单"
      width="500px"
      destroy-on-close
    >
      <div v-if="currentProduct" class="order-form-container">
        <el-form
          ref="orderFormRef"
          :model="orderForm"
          :rules="orderRules"
          label-width="100px"
          label-position="right"
        >
          <div class="order-product-info">
            <div class="order-product-image">
              <img :src="formatImageUrl(currentProduct.image)" alt="产品图片" />
            </div>
            <div class="order-product-details">
              <h3>{{ currentProduct.name }}</h3>
              <p class="order-product-price">¥{{ currentProduct.price }} / {{ currentProduct.unit }}</p>
              <p class="order-product-stock">库存: {{ currentProduct.stock }} {{ currentProduct.unit }}</p>
              <p class="order-product-farmer">农户: {{ currentProduct.farmerName }}</p>
            </div>
          </div>
          
          <el-divider />
          
          <el-form-item label="购买数量" prop="quantity">
            <el-input-number
              v-model="orderForm.quantity"
              :min="1"
              :max="Math.max(1, currentProduct.stock)"
              :precision="0"
              :step="1"
              style="width: 100%"
              @change="calculateTotal"
            />
          </el-form-item>
          
          <el-form-item label="收货地址" prop="address">
            <el-input v-model="orderForm.address" type="textarea" :rows="2" />
          </el-form-item>
          
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="orderForm.phone" />
          </el-form-item>
          
          <el-form-item label="备注" prop="note">
            <el-input v-model="orderForm.note" type="textarea" :rows="2" />
          </el-form-item>
          
          <div class="order-total">
            <span class="total-label">订单总额:</span>
            <span class="total-value">¥{{ orderTotal }}</span>
          </div>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitLoading">提交订单</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  ShoppingBag, Search, Filter, Refresh, Location, Phone, ShoppingCart, Picture
} from '@element-plus/icons-vue';
import { useBuyerStore } from '../../store';
import { format } from 'date-fns';

// 路由和状态管理
const router = useRouter();
const buyerStore = useBuyerStore();
const defaultProductImage = 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png';

// 列表数据
const loading = ref(false);
const products = ref([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(12);

// 筛选表单
const filterForm = reactive({
  productType: '',
  priceRange: '',
  sort: 'timeDesc'
});

// 对话框控制
const productDetailVisible = ref(false);
const orderDialogVisible = ref(false);
const currentProduct = ref(null);
const submitLoading = ref(false);

// 订单表单
const orderFormRef = ref(null);
const orderForm = reactive({
  quantity: 1,
  address: '',
  phone: '',
  note: ''
});

// 订单表单验证规则
const orderRules = {
  quantity: [
    { required: true, message: '请输入购买数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 格式化图片URL
const formatImageUrl = (url) => {
  if (!url) return defaultProductImage;
  
  // 如果是相对URL，添加API前缀
  if (url.startsWith('/file/') || url.startsWith('/api/file/')) {
    const token = localStorage.getItem('token');
    const apiUrl = url.startsWith('/api') ? url : `/api${url}`;
    
    if (token) {
      return `${apiUrl}?token=${encodeURIComponent(token)}`;
    }
    return apiUrl;
  }
  
  return url;
};

// 计算订单总额
const orderTotal = computed(() => {
  if (!currentProduct.value || !orderForm.quantity) return 0;
  return (currentProduct.value.price * orderForm.quantity).toFixed(2);
});

// 过滤产品列表
const filteredProducts = computed(() => {
  if (!products.value.length) return [];
  
  let result = [...products.value];
  
  // 按关键词搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(product => {
      return product.name.toLowerCase().includes(query) || 
             product.category.toLowerCase().includes(query) ||
             product.farmerName.toLowerCase().includes(query);
    });
  }
  
  // 按产品类型筛选
  if (filterForm.productType) {
    result = result.filter(product => product.category === filterForm.productType);
  }
  
  // 按价格区间筛选
  if (filterForm.priceRange) {
    const range = filterForm.priceRange.split('-');
    if (range.length === 2) {
      const min = parseFloat(range[0]);
      const max = parseFloat(range[1]);
      result = result.filter(product => product.price >= min && product.price <= max);
    } else if (filterForm.priceRange === '50+') {
      result = result.filter(product => product.price >= 50);
    }
  }
  
  // 排序
  result.sort((a, b) => {
    switch (filterForm.sort) {
      case 'priceAsc':
        return a.price - b.price;
      case 'priceDesc':
        return b.price - a.price;
      case 'salesDesc':
        return (b.salesCount || 0) - (a.salesCount || 0);
      case 'timeDesc':
        return new Date(b.createTime || 0) - new Date(a.createTime || 0);
      default:
        return 0;
    }
  });
  
  return result;
});

// 分页后的产品列表
const displayedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredProducts.value.slice(start, end);
});

// 应用筛选
const applyFilter = () => {
  currentPage.value = 1;
};

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    productType: '',
    priceRange: '',
    sort: 'timeDesc'
  });
  searchQuery.value = '';
  currentPage.value = 1;
};

// 查看产品详情
const viewProductDetail = (product) => {
  // 判断产品类型
  let sellerType = determineProductType(product);
  
  // 设置当前产品和类型
  currentProduct.value = {
    ...product,
    sellerType: sellerType
  };
  
  console.log('当前产品详情:', currentProduct.value);
  productDetailVisible.value = true;
};

// 判断产品类型
const determineProductType = (product) => {
  // 判断产品来源：农户还是卖家
  // 如果有farmerId、farmer_id或farmerName字段，则为农户产品
  if (product.farmerId || product.farmer_id || product.farmerName) {
    return 'farmer';
  }
  
  // 如果有sellerId、seller_id或sellerName字段，则为卖家产品
  if (product.sellerId || product.seller_id || product.sellerName) {
    return 'seller';
  }
  
  // 根据产品特征判断
  // 卖家产品通常会有这些字段
  if (product.origin && product.productionDate && product.shelfLife) {
    return 'seller';
  }
  
  // 农户产品通常会有种植相关字段
  if (product.plantingMethod || product.harvestDate || product.freshnessDays) {
    return 'farmer';
  }
  
  // 如果无法确定，默认为农户产品
  return 'farmer';
};

// 联系农户
const contactFarmer = (product) => {
  ElMessageBox.alert(
    `农户电话: ${product.farmerPhone}`,
    '联系信息',
    {
      confirmButtonText: '确定'
    }
  );
};

// 创建订单
const createOrder = (product) => {
  console.log('创建订单，产品数据：', product);
  console.log('产品库存：', product.stock, typeof product.stock);
  
  currentProduct.value = product;
  
  // 如果库存为0或负数，提示库存不足
  if (!product.stock || product.stock <= 0) {
    ElMessage.warning('该产品库存不足，无法下单');
    return;
  }
  
  // 尝试获取用户信息或上次使用的地址和电话
  const savedAddress = localStorage.getItem('lastUsedAddress') || '';
  const savedPhone = localStorage.getItem('lastUsedPhone') || '';
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  
  // 初始化订单表单
  Object.assign(orderForm, {
    quantity: 1,
    address: savedAddress,
    phone: savedPhone || userInfo.phone || '',
    note: ''
  });
  
  orderDialogVisible.value = true;
  productDetailVisible.value = false;
};

// 计算总金额
const calculateTotal = () => {
  if (!currentProduct.value || !orderForm.quantity) return;
  // 订单总额通过计算属性自动更新
};

// 提交订单
const submitOrder = async () => {
  if (!orderFormRef.value) return;
  
  await orderFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    // 检查库存是否足够
    if (currentProduct.value.stock <= 0) {
      ElMessage.error('产品库存不足，无法下单');
      return;
    }
    
    if (orderForm.quantity > currentProduct.value.stock) {
      ElMessage.error(`购买数量不能超过库存数量（${currentProduct.value.stock}）`);
      return;
    }
    
    try {
      submitLoading.value = true;
      
      // 准备订单数据，确保数值类型正确
      const orderData = {
        farmerId: Number(currentProduct.value.farmerId),
        sellerId: Number(currentProduct.value.farmerId),
        farmerName: currentProduct.value.farmerName,
        sellerName: currentProduct.value.farmerName,
        farmerPhone: currentProduct.value.farmerPhone,
        sellerPhone: currentProduct.value.farmerPhone,
        productId: Number(currentProduct.value.id),
        productName: currentProduct.value.name,
        productImage: currentProduct.value.image || '',
        quantity: Number(orderForm.quantity),
        unit: currentProduct.value.unit || '件',
        price: Number(currentProduct.value.price),
        totalAmount: Number(orderTotal.value),
        address: orderForm.address,
        phone: orderForm.phone,
        contactName: orderForm.address.split(' ')[0] || '用户',
        contactPhone: orderForm.phone,
        remark: orderForm.note || '',
        orderType: 0 // 明确标注为农产品订单类型
      };
      
      console.log('提交订单数据:', orderData); // 调试输出
      
      // 创建订单
      const result = await buyerStore.createOrder(orderData);
      
      // 保存地址和电话以便下次使用
      localStorage.setItem('lastUsedAddress', orderForm.address);
      localStorage.setItem('lastUsedPhone', orderForm.phone);
      
      ElMessage.success('订单创建成功');
      orderDialogVisible.value = false;
      
      // 询问是否跳转到订单页面
      ElMessageBox.confirm(
        '订单已创建成功，是否前往订单管理页面查看？',
        '订单创建成功',
        {
          confirmButtonText: '前往订单页面',
          cancelButtonText: '继续浏览',
          type: 'success'
        }
      ).then(() => {
        router.push('/main/buyer/orders');
      }).catch(() => {});
      
    } catch (error) {
      console.error('提交订单失败', error);
      ElMessage.error('提交订单失败: ' + (error.message || '未知错误'));
    } finally {
      submitLoading.value = false;
    }
  });
};

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 获取产品列表
const fetchProducts = async () => {
  loading.value = true;
  try {
    console.log('开始获取产品列表...');
    const productsData = await buyerStore.fetchAllProducts();
    console.log('获取到的产品列表:', productsData);
    
    // 检查每个产品是否包含stock字段
    if (productsData && productsData.length > 0) {
      productsData.forEach((product, index) => {
        console.log(`产品 ${index + 1} - ${product.name}:`, {
          id: product.id,
          price: product.price,
          stock: product.stock,
          unit: product.unit,
          category: product.category
        });
        
        // 确保stock字段存在，如果不存在则设为0
        if (product.stock === undefined || product.stock === null) {
          console.warn(`产品 ${product.name} 缺少库存信息，设置默认值为0`);
          product.stock = 0;
        }
      });
    }
    
    products.value = productsData;
  } catch (error) {
    console.error('获取产品列表失败', error);
    ElMessage.error('获取产品列表失败: ' + (error.message || '未知错误'));
    products.value = [];
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchProducts();
});
</script>

<style scoped>
.product-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
  color: var(--primary-color);
}

.search-input {
  width: 250px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.loading-container {
  padding: 20px;
}

.product-grid {
  margin-bottom: 20px;
}

.product-card {
  height: 100%;
  margin-bottom: 20px;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-image-container {
  height: 180px;
  overflow: hidden;
  border-radius: 4px 4px 0 0;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.product-stock-low {
  color: #f56c6c;
  font-size: 12px;
}

.product-stock-out {
  color: #f56c6c;
  font-size: 12px;
  font-weight: bold;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 10px;
}

.product-unit {
  font-size: 14px;
  font-weight: normal;
  color: #606266;
}

.product-stock {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.stock-highlight {
  color: #67c23a;
  font-weight: bold;
}

.stock-out {
  color: #f56c6c;
  font-weight: bold;
}

.product-farmer {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.farmer-avatar {
  margin-right: 5px;
}

.farmer-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-actions {
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 产品详情样式 */
.product-detail-header {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.product-detail-image {
  width: 300px;
  height: 300px;
  border-radius: 4px;
  overflow: hidden;
}

.product-detail-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-detail-info {
  flex: 1;
}

.detail-name {
  margin: 0 0 10px;
  font-size: 24px;
  font-weight: bold;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.detail-stock {
  color: #606266;
  font-size: 14px;
}

.detail-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  margin: 15px 0;
}

.price-value {
  font-size: 24px;
}

.detail-farmer {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.farmer-info {
  margin-left: 10px;
}

.detail-buttons {
  margin-top: 20px;
}

/* 订单表单样式 */
.order-form-container {
  padding: 10px;
}

.order-product-info {
  display: flex;
  margin-bottom: 20px;
}

.order-product-image {
  width: 80px;
  height: 80px;
  overflow: hidden;
  margin-right: 15px;
  border-radius: 4px;
}

.order-product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.order-product-details h3 {
  margin: 0 0 5px;
  font-size: 16px;
}

.order-product-price {
  color: #f56c6c;
  font-weight: bold;
  margin: 5px 0;
}

.order-product-stock,
.order-product-farmer {
  color: #606266;
  font-size: 12px;
  margin: 3px 0;
}

.order-total {
  text-align: right;
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px dashed var(--el-border-color);
}

.total-label {
  font-size: 16px;
  margin-right: 10px;
}

.total-value {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .product-detail-header {
    flex-direction: column;
  }
  
  .product-detail-image {
    width: 100%;
    height: auto;
    max-height: 300px;
  }
  
  .order-product-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .order-product-image {
    margin: 0 0 10px;
  }
}
</style> 